﻿
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sproc_GetAllChildPosition]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[sproc_GetAllChildPosition];
GO
CREATE PROCEDURE [dbo].[sproc_GetAllChildPosition] 
    @Position_ID int
/*

======================================================
功能:    得到此职位所有的子职位
参数:
    @Position_id int        :    职位ID
======================================================

*/
AS
BEGIN
SET NOCOUNT ON

declare @subtree table ( Position_ID int not null );

-- Select all recursive child positions
with Position_Subtree( Position_ID )
as
(
    select p.Position_ID
    from dbo.UDS_Position p
    where p.Super_Position_ID = @Position_ID and p.Position_ID <> p.Super_Position_ID

    union all

    select p.Position_ID
    from dbo.UDS_Position p join Position_Subtree ps on p.Super_Position_ID = ps.Position_ID
)
insert into @subtree ( Position_ID )
select Position_ID
from Position_Subtree;

-- Finally, return all the records
select
    p.*
from
    dbo.UDS_Position p,
    @subtree t
where
    p.Position_ID = t.Position_ID;

END
GO